package com.wisdom.benefit.jufa.news;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.wisdom.benefit.jufa.R;
import com.wisdom.benefit.jufa.base.BaseActivity;
import com.wisdom.benefit.jufa.base.BaseApplication;
import com.wisdom.benefit.jufa.base.CommonDialog;
import com.wisdom.benefit.jufa.event.CallBackOtherInterface;
import com.wisdom.benefit.jufa.main.DeviceInfoModel;
import com.wisdom.benefit.jufa.main.LoginActivity;
import com.wisdom.benefit.jufa.main.MainActivity;
import com.wisdom.benefit.jufa.net.RetrofitService;
import com.wisdom.benefit.jufa.utils.CommonUtils;
import com.wisdom.benefit.jufa.utils.DataCleanManager;
import com.wisdom.benefit.jufa.widget.RefreshListView;

import java.util.ArrayList;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import cn.ycbjie.ycstatusbarlib.bar.YCAppBar;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class OrderDetailsActivity extends BaseActivity implements CallBackOtherInterface, SwipeRefreshLayout.OnRefreshListener {
    private RelativeLayout backRl;
    private RefreshListView lv;
    private OrderDetailsAdapter orderDetailsAdapter;
    private Long payeeId;
    private String orderId;
    private String orderNo, startTime, endTime;
    private double actualMoney;
    private int payType, status;
    private ArrayList<QueryUserOrderPayListBean> datas;
    private CommonDialog dialog;
    private long lastClickTime = 0;
    private long dialoglastClickTime = 0;
    private long sureMoneyTime = 0;
    private boolean isDialog = false;
    private boolean isTo = false;
    private int offset = 0;
    private int limit = 10;
    private boolean isMore = false;
    private boolean isSure = false;
    private int myPOsition = 999999999;

    @Override
    protected int getLayout() {
        return R.layout.activity_order_details;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        orderId = getIntent().getStringExtra("orderId");
        orderNo = getIntent().getStringExtra("orderNo");
        startTime = getIntent().getStringExtra("startTime");
        endTime = getIntent().getStringExtra("endTime");
        actualMoney = getIntent().getDoubleExtra("actualMoney", 0);
        payType = getIntent().getIntExtra("payType", 0);
        status = getIntent().getIntExtra("status", 0);
        datas = new ArrayList<>();
    }


    @Override
    protected void onResume() {
        super.onResume();
        isTo = false;
        offset = 0;
        isSure = true;
        datas = new ArrayList<>();
        queryUserOrderPayList(Long.valueOf(BaseApplication.getContext().getUserId()).longValue(), orderId, orderNo, actualMoney, payType, status, startTime, endTime);
    }

    @Override
    protected void initViews() {
        //返回按钮
        backRl = findViewById(R.id.order_details_back);
        //列表
        lv = findViewById(R.id.order_details_lv);
        //设置状态栏为蓝色
        YCAppBar.setStatusBarColor(OrderDetailsActivity.this,
                ContextCompat.getColor(OrderDetailsActivity.this,
                        R.color.blue));
        //确认收款
        //设置监听
        setClick();
    }

    /**
     * 监听事件
     *
     * @return
     */
    private void setClick() {
        //返回按钮
        backRl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        //刷新
        lv.setOnRefreshListener(new RefreshListView.OnRefreshListener() {
            @Override
            public void onRefresh() {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        offset = 0;
                        datas = new ArrayList<>();
                        queryUserOrderPayList(Long.valueOf(BaseApplication.getContext().getUserId()).longValue(), orderId, orderNo, actualMoney, payType, status, startTime, endTime);
                        lv.finishRefresh();
                    }
                }, 2000);
            }
        });
        lv.setOnLoadMoreListener(new RefreshListView.OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (isMore == true) {
                            offset = offset + limit;
                            queryUserOrderPayMoreList(Long.valueOf(BaseApplication.getContext().getUserId()).longValue(), orderId, orderNo, actualMoney, payType, status, startTime, endTime, offset);
                            lv.finishLoadMore();
                        } else {
                            Toast.makeText(OrderDetailsActivity.this, "已经到最后了", Toast.LENGTH_SHORT).show();
                            lv.finishLoadMore();
                        }
                    }
                }, 2000);
            }
        });


    }

    private void showListView(ArrayList<QueryUserOrderPayListBean> list) {
        if (isSure == true) {
            isSure = false;
            orderDetailsAdapter = new OrderDetailsAdapter(list, this, this);
            lv.setAdapter(orderDetailsAdapter);
        } else {
            if (orderDetailsAdapter == null) {
                orderDetailsAdapter = new OrderDetailsAdapter(list, this, this);
                lv.setAdapter(orderDetailsAdapter);
            } else {
                orderDetailsAdapter.onDateChanged(list);
            }
        }

    }

    /**
     * 订单按条件查询接口
     */
    private void queryUserOrderPayList(Long payeeId, String orderId, String orderNo, double actualMoney, int payType, int status, String startTime, String endTime) {
        String deviceId = DeviceInfoModel.getDeviceId(getActivity());
        addDisposable(RetrofitService.getNetService()
                .queryUserOrderPayList(payeeId, orderId, orderNo, actualMoney, payType, status, startTime, endTime, deviceId, 0, limit)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    if (response.getCode() == 0) {
                        for (int i = 0; i < response.getData().size(); i++) {
                            datas.add(response.getData().get(i));
                        }
                        if (response.getData().size() != 0) {
                            lv.setVisibility(View.VISIBLE);
                        }
                        if (response.getData().size() < 10) {
                            isMore = false;
                        } else {
                            isMore = true;
                        }
                        showListView(datas);
                        if (dialog != null) {
                            dialog.dismiss();
                            isDialog = false;
                        }
                    } else if (response.getCode() == -2) {
                        if (dialog != null) {
                            dialog.dismiss();
                            isDialog = false;
                        }
                        showBindToast(response.getMsg());
                        logout(BaseApplication.getContext().getUserId());
                    } else {
                        if (dialog != null) {
                            dialog.dismiss();
                            isDialog = false;
                        }
                        showBindToast(response.getMsg());
                    }
                }, throwable -> {
                    if (dialog != null) {
                        dialog.dismiss();
                        isDialog = false;
                    }
                    throwable.printStackTrace();
                    hideProgressDialog();
                    if (CommonUtils.isNetworkAvailable(getContext()))
                        showBindToast("查询失败");
                    else
                        showBindToast("无网络连接，请稍后再试");
                }));
    }

    /**
     * 订单按条件查询接口
     */
    private void queryUserOrderPayMoreList(Long payeeId, String orderId, String orderNo, double actualMoney, int payType, int status, String startTime, String endTime, int offset) {
        String deviceId = DeviceInfoModel.getDeviceId(getActivity());
        addDisposable(RetrofitService.getNetService()
                .queryUserOrderPayList(payeeId, orderId, orderNo, actualMoney, payType, status, startTime, endTime, deviceId, offset, limit)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    if (response.getCode() == 0) {
                        for (int i = 0; i < response.getData().size(); i++) {
                            datas.add(response.getData().get(i));
                        }
                        if (response.getData().size() != 0) {
                            lv.setVisibility(View.VISIBLE);
                        }
                        if (response.getData().size() < 10) {
                            isMore = false;
                        } else {
                            isMore = true;
                        }
                        showListView(datas);
                        if (dialog != null) {
                            dialog.dismiss();
                            isDialog = false;
                        }
                    } else if (response.getCode() == -2) {
                        if (dialog != null) {
                            dialog.dismiss();
                            isDialog = false;
                        }
                        showBindToast(response.getMsg());
                        logout(BaseApplication.getContext().getUserId());
                    } else {
                        if (dialog != null) {
                            dialog.dismiss();
                            isDialog = false;
                        }
                        showBindToast(response.getMsg());
                    }
                }, throwable -> {
                    if (dialog != null) {
                        dialog.dismiss();
                        isDialog = false;
                    }
                    throwable.printStackTrace();
                    hideProgressDialog();
                    if (CommonUtils.isNetworkAvailable(getContext()))
                        showBindToast("查询失败");
                    else
                        showBindToast("无网络连接，请稍后再试");
                }));
    }

    /**
     * 推出登陆
     */
    private void logout(String userId) {
        showProgressDialog("");
        addDisposable(RetrofitService.getNetService()
                .logout(userId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    hideProgressDialog();
                    if (response.getCode() == 0) {
                        //步骤1：创建一个SharedPreferences对象
                        SharedPreferences sharedPreferences = getActivity().getSharedPreferences("data", Context.MODE_PRIVATE);
                        //步骤2： 实例化SharedPreferences.Editor对象
                        SharedPreferences.Editor editor = sharedPreferences.edit();
                        //步骤3：将获取过来的值放入文件
                        editor.putString("isHaveLogin", "0");
                        //步骤4：提交
                        editor.commit();
                        BaseApplication.getContext().setDeviceId("");
                        Intent intent = new Intent(getActivity(), LoginActivity.class);
                        MainActivity.mainActivity.finish();
                        startActivity(intent);
                        getActivity().finish();
                    } else {
                        showBindToast(response.getMsg());
                    }
                }, throwable -> {
                    throwable.printStackTrace();
                    hideProgressDialog();
                    if (CommonUtils.isNetworkAvailable(getContext()))
                        showBindToast("退出失败");
                    else
                        showBindToast("无网络连接，请稍后再试");
                }));
    }


    @Override
    protected int getTitleStringRes() {
        return 0;
    }

    @Override
    public void callBackClick(int position) {
        if (isTo == false) {
            isTo = true;
            Intent intent = new Intent(OrderDetailsActivity.this, UploadCredentialsActivity.class);
            intent.putExtra("PayeeId", datas.get(position).getPayeeId());
            intent.putExtra("OrderId", datas.get(position).getOrderId());
            intent.putExtra("ReceiptStatus", datas.get(position).getReceiptStatus());
            intent.putExtra("PayeeTurn", datas.get(position).getPayeeTurn());
            startActivity(intent);
        }
    }

    @Override
    public void callBackClickOther(int position) {
        if (myPOsition == 999999999) {
            myPOsition = position;
            initDialog(position);
        } else if (myPOsition == position) {
            myPOsition = position;
            long now = System.currentTimeMillis();
            if (now - lastClickTime > 2000) {
                lastClickTime = now;
                initDialog(position);
            }
        } else {
            myPOsition = position;
            initDialog(position);
        }


    }

    @Override
    public void callIvBackClick(int position) {

    }

    /**
     * 确认收款
     */
    private void confirmReceipt(Long payeeId, int position) {
        showProgressDialog("");
        addDisposable(RetrofitService.getNetService()
                .confirmReceipt(payeeId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    hideProgressDialog();
                    if (response.getCode() == 0) {
                        offset = 0;
                        isSure = true;
                        datas = new ArrayList<>();

                        queryUserOrderPayList(Long.valueOf(BaseApplication.getContext().getUserId()).longValue(), orderId, orderNo, actualMoney, payType, status, startTime, endTime);

                    } else {
                        showBindToast(response.getMsg());
                    }
                }, throwable -> {
                    throwable.printStackTrace();
                    hideProgressDialog();
                    if (CommonUtils.isNetworkAvailable(getContext()))
                        showBindToast("确认收款失败");
                    else
                        showBindToast("无网络连接，请稍后再试");
                }));
    }

    @Override
    public void onRefresh() {
//        new Handler().postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                refreshLayout.setVisibility(View.VISIBLE);
//                refreshLayout.setRefreshing(false);
//                queryUserOrderPayList(Long.valueOf(BaseApplication.getContext().getUserId()).longValue(), orderId, orderNo, actualMoney, payType, status, startTime, endTime);
//            }
//        }, 1000);
    }

    private void initDialog(int position) {
        dialog = new CommonDialog(OrderDetailsActivity.this);
        dialog.setMessage("是否确认收款")
                .setTitle("提示")
                .setOnClickBottomListener(new CommonDialog.OnClickBottomListener() {
                    @Override
                    public void onPositiveClick(String message) {
                        long now = System.currentTimeMillis();
                        if (now - dialoglastClickTime > 2000) {
                            dialoglastClickTime = now;
                            boolean b = DataCleanManager.clearAllCache(OrderDetailsActivity.this);
                            double num = datas.get(position).getOrderMoney();
                            double num1;
                            if (TextUtils.isEmpty(message)) {
                                num1 = Double.parseDouble("0");
                            } else {
                                num1 = Double.parseDouble(message);
                            }
                            if (num == num1) {

                                confirmReceipt(datas.get(position).getId(), position);

                            } else {
                                Toast.makeText(OrderDetailsActivity.this, "当前输入金额与订单金额不符", Toast.LENGTH_SHORT).show();
                            }
                        }
                    }

                    @Override
                    public void onNegtiveClick() {
                        dialog.dismiss();
                    }
                }).

                show();
    }
}
